/*
 * Created by SharpDevelop.
 * User: David
 * Date: 2006-11-24
 * Time: 23:03
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Diagnostics;

using Labb4.Pooman.Players;

namespace Labb4.Pooman.Game
{
	/// <summary>
	/// The state of game phase 2
	/// 
	/// Implements the State design pattern
	/// </summary>
	public class GameStatePhase2 : GameState
	{
		#region constructors
		
		public GameStatePhase2(PoomanMain poo) :
			base(poo)
		{
		}
		
		#endregion
		
		#region overrides
		
		/// <summary>
		/// This phase has no implementation for this method
		/// Maybe make this virtual then, and move the unimplemented version of this method
		/// to the base class GameState
		/// </summary>
		public override void LastActionOfThePhase()
		{
		}
		
		/// <summary>
		/// Collects cards from all players until there are as many plays on the table as there are active
		/// players at the start of the play. When this criteria has been met, the cards are removed,
		/// and a new stick can begin. The last player to act in a stick, is the first to act in the next
		/// stick.
		/// </summary>
		/// <param name="deltaTime">The time passed since the last time this method was called</param>
		public override void PlayNextStick(int deltaTime)
		{
			if(!m_FoundWinnerOfLastStick)
			{
				if(m_Stick.GetLastPlayer(ref m_Swarm))
				{
					m_FoundWinnerOfLastStick = true;
				}
				
				if(m_PlayerManager.GetPooman() != null)
				{
					Debug.WriteLine("Me thinks we have found a winner..");
					m_PoomanMain.SwitchPhase();
				}
			}
			else
			{
				m_CounterForDisplayingWonCards += deltaTime;
				
				if(m_CounterForDisplayingWonCards > Properties.Instance.DisplayTimeForWonCards)
				{
					m_CounterForDisplayingWonCards = 0;
					m_FoundWinnerOfLastStick = false;
					
					Player winner = m_Stick.Winner;
					m_Swarm.Clear(); //TODO why? it should be empty..
					
					Table.Instance.TurnCards();
					m_Stick.Clear();
					
					m_PlayerManager.GetNextSwarm(winner, m_Swarm);
					
					if(m_Swarm.Count == 1)
					{
						//if only one player was added to the swarm, this means that we have found
						//our Pooman. 'Cause this is the last player who still has cards on hand
						m_PoomanMain.SwitchPhase();
					}
				}
			}
		}
		
		/// <summary>
		/// Resets the phase to the start values of this phase
		/// </summary>
		/// <param name="firstPlayerInSwarm">Reference to the player who should be first to act in this phase</param>
		public override void ResetPhase(Player firstPlayerInSwarm)
		{
			base.ResetPhase(firstPlayerInSwarm);
			
			m_PlayerManager.GetNextSwarm(firstPlayerInSwarm, m_Swarm);
		}
		
		#endregion
	}
}
